<?php
/**
 * admin端素材库
 */
namespace App\Http\Controllers;

use App\Models\Attachment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Kuyuan\Phpwidget\File;

class AttachmentController extends Controller
{
    /**
     * 上传素材
     */
    public function upload(Request $request)
    {
        $File = $request->file('file');
        $_absolute_path = $File->store(File::stringDir('images'));
        $Attachment = Attachment::create(array(
            'carrier_id' => 0,
            'uid' => auth()->id(),
            'filename' => $File->getClientOriginalName(),
            'attachment' => $_absolute_path
        ));
        return response([
            'data' => $Attachment
        ]);
    }

    /**
     * 获取附件列表
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function getList(Request $request)
    {
        $Attachment = Attachment::where('carrier_id',$request->carrier_id)
            ->where('type',$request->type)
            ->orderBy('id','desc')
            ->offset($request->limit[0])
            ->limit($request->limit[1])
            ->get();
        return response([
            "data"=>$Attachment
        ]);
    }

    /**
     * 获取系统附件url链接
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function getAttachmentUrl()
    {
        return response([
            "data" => config('app.url').'/storage/'
        ]);
    }

    /**
     * 删除素材附件
     * @param int $_attachment_id 附件素材id
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function delete($_attachment_id)
    {
        DB::beginTransaction();
        try{
            $Attachment = Attachment::find($_attachment_id);
            unlink(storage_path('app/public/'.$Attachment->attachment));
            $Attachment->delete();
            DB::commit();
            return response('删除成功');
        }catch (\PDOException $e) {
            DB::rollBack();
            return response('删除失败', 401);
        }
    }
}
